/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.softcomputo.dao.impl;

import com.softcomputo.commons.exception.DataAccessRuntimeException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.apache.log4j.Logger;

/**
 * Clase base para los DAOs JDBC
 *
 * @author JGONZA7
 */
public abstract class AbstractJdbcDao {

    private static final Logger LOGGER
            = Logger.getLogger(AbstractJdbcDao.class);

    private DataSource dataSource;

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    protected Connection getConnection() throws SQLException {
        if (this.getDataSource() == null) {
            throw new IllegalStateException("No DataSource Defined!");
        }
        return this.getDataSource().getConnection();
    }

    protected void closeResources(PreparedStatement pstm, ResultSet rs,
            Connection connection) {
        this.releaseResources(connection, pstm,rs);
    }

    protected void releaseResources(Connection connection, Object... resources) {
        for (Object resource : resources) {
            try {
                if (resource instanceof Statement) {
                    Statement stm = (Statement)resource;
                    stm.close();
                }
                if (resource instanceof PreparedStatement) {
                    PreparedStatement pstm = (PreparedStatement)resource;
                    pstm.close();
                }
                if (resource instanceof ResultSet) {
                    ResultSet rs = (ResultSet)resource;
                    rs.close();
                }
            } catch (Exception ex) {
                LOGGER.error(String.format("Error close resource '%s'",
                        resource.getClass().toString()),ex);
            }           
        }

        try {
            if (connection != null) {
                connection.close();
            }
        } catch (Exception ex) {
            throw new DataAccessRuntimeException(ex.getMessage(), ex);
        }
    }
}
